package hu.genius;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class SQLExampleActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Log.d("m", "1");
		ScrollView actionView = (ScrollView) findViewById(R.id.actionLayout);
		Log.d("m", "2");
		actionView.addView(doActionRow(listActions()));
	}

	private List<Product> listActions() {
		Log.d("m", "21");
		DBAdapter db = new DBAdapter(this);
		db.open();
		Cursor c = db.getAllProducts();
		Log.d("m", "22");
		List<Product> products = new ArrayList<Product>();
		if (c.moveToFirst()) {
			do {
				Product product = new Product();
				product.setId(c.getInt(0));
				product.setName(c.getString(1));
				product.setPrice(c.getInt(2));
				product.setImage(c.getString(3));
				products.add(product);
			} while (c.moveToNext());
		}
		Log.d("m", "23");
		db.close();
		return products;
	}

	private View doActionRow(List<Product> productList) {
		LinearLayout actionLayout = new LinearLayout(this);
		actionLayout.setOrientation(LinearLayout.VERTICAL);
		for (Product product : productList) {
			LinearLayout rowLayout = new LinearLayout(this);
			rowLayout.setOrientation(LinearLayout.HORIZONTAL);

			ImageView productView = new ImageView(this);
			productView.setPadding(getDpSize(5), getDpSize(5), getDpSize(5),
					getDpSize(5));
			productView.setImageBitmap(loadImage(product.getImage()));
			productView.setLayoutParams(new LinearLayout.LayoutParams(
					getDpSize(110), getDpSize(110)));
			rowLayout.addView(productView);

			LinearLayout textLayout = new LinearLayout(this);
			textLayout.setOrientation(LinearLayout.VERTICAL);

			TextView nameView = new TextView(this);
			nameView.setText(product.getName());
			textLayout.addView(nameView);

			TextView priceView = new TextView(this);
			priceView.setText(product.getPrice() + "");
			textLayout.addView(priceView);

			rowLayout.addView(textLayout);

			actionLayout.addView(rowLayout);
		}

		return actionLayout;
	}

	public int getDpSize(float dp) {
		DisplayMetrics metrics = this.getResources().getDisplayMetrics();
		int pixels = (int) (metrics.density * dp + 0.5f);
		return pixels;
	}

	public Bitmap loadImage(String source) {
		try {
			InputStream is = getAssets().open("images/" + source + ".jpg");
			return BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}